Dart Map operator []=
Syntax & Examples


Syntax of Map.operator []=

The syntax of Map.operator []= operator is:

operator []=(K key, V value) → void

This operator []= operator of Map associates the key with the given value.

Parameters

ParameterOptional/RequiredDescription
keyrequiredthe key to associate with the value
valuerequiredthe value to be associated with the key


✐ Examples

1 Update ages in a map

In this example,

  1. We create a map ages containing names and ages.
  2. We use the operator []= to associate the key 'Charlie' with the value 35 in the ages map.
  3. We print the updated ages map to standard output.

Dart Program

void main() {
  Map<String, int> ages = {'Alice': 30, 'Bob': 25};
  ages['Charlie'] = 35;
  print('Updated ages: $ages');
}

Output

Updated ages: {Alice: 30, Bob: 25, Charlie: 35}

2 Update names in a map

In this example,

  1. We create a map names containing integers and corresponding names.
  2. We use the operator []= to associate the key 3 with the value 'Charlie' in the names map.
  3. We print the updated names map to standard output.

Dart Program

void main() {
  Map<int, String> names = {1: 'Alice', 2: 'Bob'};
  names[3] = 'Charlie';
  print('Updated names: $names');
}

Output

Updated names: {1: Alice, 2: Bob, 3: Charlie}

3 Update prices in a map

In this example,

  1. We create a map prices containing item names and prices.
  2. We use the operator []= to associate the key 'Cherry' with the value 3.0 in the prices map.
  3. We print the updated prices map to standard output.

Dart Program

void main() {
  Map<String, double> prices = {'Apple': 2.5, 'Banana': 1.75};
  prices['Cherry'] = 3.0;
  print('Updated prices: $prices');
}

Output

Updated prices: {Apple: 2.5, Banana: 1.75, Cherry: 3.0}

Summary

In this Dart tutorial, we learned about operator []= operator of Map: the syntax and few working examples with output and detailed explanation for each example.